const express = require("express");
const { db } = require("../database");

// const { validate, validators } = require("../validate");
// // jwt
// const { getPayloadByToken } = require("../jwt");
// const { makePassword } = require("../utils");

// 创建路由对象，使得用户登录状态检查的中间件只作用于部分路由。
const router = express.Router();
// 导入用户登录状态检查的中间件
const { useAuthorization } = require("./base");
router.use(useAuthorization);

router
    /**
     * 查询角色信息
    */
    .get('/', async (req, res) => {
        res.send({
            code: 200,
            message: "角色查询成功",
            result: req.body,
        })

    })
    /**
     * 新建角色
     */
    .post(
        "/", async (req, res) => {
            const { rolename } = req.body;
            // console.log(rolename);
            const query = `select * from role where rolename = ${rolename}`;
            if (query) {
                res.send({
                    code: -1,
                    message: "角色已存在",
                })
            }
            const id = await db.insert(
                "insert into role (rolename) values (?)",
                rolename
            );
            const role = await db.findOne`select * from role where id = ${id}`;
            res.send({
                code: 200,
                message: "角色创建成功",
                result: role,
            });
        }
    )
    /**
     * 修改角色信息
     */
    .put(
        "/:tid",
        async (req, res) => {
            // console.log("->", req.user.id);
            let role =
                await db.findOne`select * from role where id = ${req.params.tid}`;
            if (!role) {
                return res.send({ code: -1, message: "该角色信息不存在！" });
            }
            const { rolename } = req.body;
            await db.run`update role set rolename = ${rolename} where id = ${req.params.tid}`;
            role = await db.findOne`select * from role where id = ${req.params.tid}`;
            res.send({
                code: 200,
                message: "角色修改成功",
                result: role,
            });
        }
    )
    .delete("/:tid", async (req, res) => {
        const role =
            await db.findOne`select * from role where id = ${req.params.tid}`;
        if (!role) {
            return res.send({ code: -1, message: "该角色信息不存在！" });
        }
        // 删除 role 记录
        await db.run`delete from role where id = ${req.params.tid}`;
        res.send({
            code: 200,
            message: "删除成功",
        });
    })

// 将路由作为中间件挂接在 / 根路由上。
const registerRouter = (app) => app.use("/role", router);

module.exports = { registerRouter };
